import datetime
import json

from decimal import Decimal
from bson import ObjectId


class JSONEncoder(json.JSONEncoder):
    """
        解决mongodb id为ObjectID问题
    """

    def default(self, obj):
        if isinstance(obj, ObjectId):  # 对ObjectId
            return str(obj)
        if isinstance(obj, datetime.datetime):  # 对datetime.datatime处理
            return obj.strftime('%Y-%m-%d %H:%M:%S')

        if isinstance(obj, Decimal):
            return float(obj)

        return json.JSONEncoder.default(self, obj)
